<?php
/**
 * Config.php
 *
 * @category    Madoqua
 * @package     Module
 * @subpackage  BlogAdmin
 */

/**
 * BlogAdmin_Config
 *
 * @category    Madoqua
 * @package     Module
 * @subpackage  BlogAdmin
 */
class BlogAdmin_Config
{
    /**
     * save a config file,
     *
     * we have to do this the stupid way :(
     *
     * @param Zend_Config_Xml $config
     * @param string $fileName
     */
    public static function save($config, $fileName)
    {
        $xml = self::fromArray($config->toArray());
        //parse it
        $xml->asXml($fileName);
        //and save it
    }

    /**
     * save application config
     *
     * @return void
     */
    public static function saveApplicationConfig() {
        $file = Madoqua_Application::getApplicationDirectory() . DIRECTORY_SEPARATOR .  'config/madoqua.xml';
        //config file

        self::save(Madoqua_Application::getConfiguration(), $file);
        //save it!
    }

    /**
     * get a simpleXml element from an array
     *
     * @param array $data
     * @param SimpleXMLElement $element
     * @return SimpleXMLElement
     */
    public static function fromArray($data, $element = null)
    {
        if ($element == null) {
            //we're at the start
            $element = new SimpleXMLElement('<config></config>');
            //the root element (always called "config")
        }

        foreach($data as $key => $value) {
            if (substr($key, 0, 1) == '_') {
                continue;
                //skip values starting with an underscore
            }

            if (is_array($value)) {
                //add an array of nodes
                $newElement = $element->addChild($key);
                //add a new element
                self::fromArray($value, $newElement);
                //recursion
            } else {
                //just one node
                $element->addChild($key, $value);
            }

        }

        return $element;
        //return the new element formed
    }
}